<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">歌手名称</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="歌手名称"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">描述</label>
        <el-input
          v-model="query.description"
          clearable
          placeholder="描述"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="歌手名称" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="背景图片">
            <el-button type="text" @click="searchImage">设置背景图片</el-button>
            <!-- <el-input v-model="form.bgUrlData" :rows="3" type="textarea" style="width: 370px;" /> -->
          </el-form-item>
          <!-- <el-form-item label="扩展信息">
            <el-input v-model="form.extData" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>-->
          <el-form-item label="状态">
            <el-radio-group v-model="form.enabled">
              <el-radio
                v-for="item in dict.singer_status"
                :key="item.id"
                :label="item.value"
              >{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <el-dialog
        width="65%"
        title="查看背景图片"
        :visible.sync="bgImgDialogVisible2"
        :close-on-click-modal="false"
      >
        <el-row>
          <el-col :span="24">
            <el-row>
              <ul class="list" style="overflow:auto">
                <li v-for="(item,i) in selectedBgUrlList" :key="i" class="list-item">
                  <img :src="item.smallUrl" class="bg_image">
                </li>
              </ul>
            </el-row>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog
        width="65%"
        title="设置背景图片"
        :visible.sync="bgImgDialogVisible"
        :close-on-click-modal="false"
      >
        <el-row>
          <el-col :span="8">
            <el-row>
              <el-link type="primary">已选择的图片</el-link>
            </el-row>
            <el-row>
              <ul class="list" style="overflow:auto">
                <li v-for="(item,i) in selectedBgUrlList" :key="i" class="list-item">
                  <img :src="item.smallUrl" class="bg_image" @click="removeImg(item)">
                </li>
              </ul>
            </el-row>
          </el-col>
          <el-col :span="16">
            <el-row>
              <el-input v-model="keyword" placeholder="请输入歌手" @change="searchImage" />
            </el-row>
            <el-row>
              <ul v-infinite-scroll="loadImage" class="list" style="overflow:auto">
                <li v-for="(item,i) in bgUrlList" :key="i" class="list-item">
                  <img :src="item.smallUrl" class="bg_image" @click="addImg(item)">
                </li>
              </ul>
            </el-row>
          </el-col>
        </el-row>

        <span slot="footer" class="dialog-footer">
          <el-button @click="bgImgDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="bgImgDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="主键ID" />
        <el-table-column prop="name" label="歌手名称" />
        <el-table-column prop="description" label="描述" />
        <!-- <el-table-column prop="bgUrlData" label="背景图片" /> -->
        <!-- <el-table-column prop="extData" label="扩展信息" /> -->
        <el-table-column prop="enabled" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.enabled)"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-permission="['admin','musicSinger:edit','musicSinger:del']"
          label="操作"
          width="250px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
            <el-button
              v-permission="permission.edit"
              size="mini"
              type="primary"
              icon="el-icon-picture"
              title="查看背景图片"
              @click="viewImage(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudMusicSinger from '@/api/music/musicSinger'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = {
  id: null,
  name: null,
  description: null,
  bgUrlData: null,
  extData: null,
  enabled: 'true'
}
export default {
  name: 'MusicSinger',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['singer_status'],
  cruds() {
    return CRUD({
      title: '歌手',
      url: 'api/musicSinger',
      idField: 'id',
      sort: 'id,desc',
      optShow: {
        add: true,
        edit: true,
        del: true,
        download: false,
        reset: true
      },
      crudMethod: { ...crudMusicSinger }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'musicSinger:add'],
        edit: ['admin', 'musicSinger:edit'],
        del: ['admin', 'musicSinger:del']
      },
      rules: {
        name: [{ required: true, message: '歌手名称不能为空', trigger: 'blur' }]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '歌手名称' },
        { key: 'description', display_name: '描述' }
      ],
      enabledTypeOptions: [
        { key: 'true', display_name: '启用' },
        { key: 'false', display_name: '禁用' }
      ],
      bgImgDialogVisible: false,
      bgImgDialogVisible2: false,
      loading: false,
      pageNum: 0,
      keyword: '',
      bgUrlList: [],
      selectedBgUrlList: []
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToCU](crud, form) {
      form.enabled = `${form.enabled}`

      this.loadSelectedImage(form.bgUrlData)
    },
    [CRUD.HOOK.beforeValidateCU](crud) {
      crud.form.bgUrlData = JSON.stringify(this.selectedBgUrlList)
      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm(
        '此操作将 "' +
          this.dict.label.singer_status[val] +
          '" ' +
          data.name +
          '歌手, 是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          crudMusicSinger
            .edit(data)
            .then(res => {
              this.crud.notify(
                this.dict.label.singer_status[val] + '成功',
                CRUD.NOTIFICATION_TYPE.SUCCESS
              )
            })
            .catch(err => {
              data.enabled = !data.enabled
              console.log(err.response.data.message)
            })
        })
        .catch(() => {
          data.enabled = !data.enabled
        })
    },
    viewImage(row) {
      console.log(row)
      this.bgImgDialogVisible2 = true
      this.loadSelectedImage(row.bgUrlData)
    },
    searchImage() {
      this.keyword = this.form.name
      this.bgImgDialogVisible = true
      this.bgUrlList = []
      this.pageNum = 0
      this.loadImage()
    },
    loadImage() {
      if (this.keyword === '') {
        return
      }
      this.loading = true
      this.pageNum++
      crudMusicSinger.loadImg(this.pageNum, 12, this.keyword).then(data => {
        this.loading = false
        this.bgUrlList.push(...data)
      })
    },
    clickImg(model) {
      this.addImg(model)
    },
    addImg(model) {
      const list = this.selectedBgUrlList.filter(function(m, index) {
        return m.id == model.id
      })
      if (list == null || list.length < 1) {
        this.selectedBgUrlList.push(model)
      }
    },
    removeImg(model) {
      let i = -1
      const list = this.selectedBgUrlList.filter(function(m, index) {
        if (m.id == model.id) {
          i = index
          return true
        }
        return false
      })
      if (i > -1) {
        this.selectedBgUrlList.splice(i, 1)
      }
    },
    loadSelectedImage(json) {
      this.selectedBgUrlList = []
      if (json) {
        const array = JSON.parse(json)
        if (array !== null && array.length > 0) {
          this.selectedBgUrlList.push(...array)
        }
      }
    }
  }
}
</script>

<style scoped>
.bg_image {
  width: 254px;
  height: 180px;
  cursor: pointer;
}
.list {
  height: 280px;
  list-style: none;
  margin: 0px;
  padding: 0px;
  margin-top: 20px;
}
.list-item {
  float: left;
  margin: 3px 8px;
}
</style>
